<template>
  <div :class="isComponet === true ? '' : 'app-container'">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="">
        <el-form-item label="检具编号">
          <el-input
            v-model="searchParam.detectionEquipCode"
            placeholder="请输入检具编号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="生产设备">
          <el-select
            v-model="searchParam.processEquipCode"
            placeholder="请选择生产设备编号"
            clearable
            @keyup.enter="search"
          >
            <el-option
              v-for="item in equipProduceList"
              :key="item.id"
              :label="item.equipCode"
              :value="item.equipCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="序列号">
          <el-input
            v-model="searchParam.partQrCode"
            placeholder="请选择序列号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <!-- result -->
        <!-- 检测结果 -->
        <el-form-item label="检测结果">
          <el-select
            v-model="searchParam.result"
            placeholder="请选择检测结果"
            clearable
          >
            <el-option
              v-for="item in useDictionary('EventResult')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="测量时间">
          <el-date-picker
            v-model="searchParam.detectionTimeSearch"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="getcreateTime"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button
          type="primary"
          plain
          @click="
            useDownload(
              '/pqd-etl/qDasDataQuery/export',
              'Q-DAS过程质量数据',
              searchParam
            )
          "
        >
          <template #icon><i-ep-download /></template>导出</el-button
        >
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        :cell-style="{ 'text-align': 'center' }"
        @selection-change="handleSelectionChange"
        @sort-change="onTableSortChanged"
      >
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <!-- <el-table-column
          label="检测程序id"
          prop="programId"
          min-width="100"
          show-overflow-tooltip
        /> -->
        <el-table-column
          sortable
          label="检测时间"
          prop="detectionTime"
          min-width="170"
          show-overflow-tooltip
        />
        <el-table-column
          label="生产设备"
          prop="processEquipCode"
          min-width="150"
          show-overflow-tooltip
        />
        <el-table-column
          label="检具编号"
          prop="detectionEquipCode"
          min-width="150"
          show-overflow-tooltip
        />
        <el-table-column
          label="检具名称"
          prop="detectionEquipName"
          min-width="150"
          show-overflow-tooltip
        />
        <el-table-column
          label="零件编码"
          prop="partCode"
          min-width="150"
          show-overflow-tooltip
        />
        <el-table-column
          label="序列号"
          prop="partQrCode"
          min-width="150"
          show-overflow-tooltip
        />
        <el-table-column
          label="测量代码"
          prop="detectionEvent"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="检测结果"
          prop="result"
          min-width="150"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            <el-tag v-show="scope.row.result == 1">合格</el-tag>
            <el-tag v-show="scope.row.result == 0" type="danger">不合格</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="采集时间"
          prop="createTime"
          min-width="170"
          show-overflow-tooltip
        />
        <!-- <el-table-column
          label="特性编号"
          prop="paramCode"
          min-width="150"
          show-overflow-tooltip
        />
        <el-table-column
          label="特性描述"
          prop="paramName"
          min-width="150"
          show-overflow-tooltip
        />
        <el-table-column
          label="特性序号"
          prop="paramIndex"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="特性值"
          prop="paramValue"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="特性状态"
          prop="paramValueStatus"
          min-width="100"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            {{ useDictionary("ParamValueStatus", scope.row.paramValueStatus) }}
          </template>
        </el-table-column>
        <el-table-column
          label="零件二维码"
          prop="partQrCode"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          label="检测事件"
          prop="detectionEvent"
          min-width="150"
          show-overflow-tooltip
        />
        <el-table-column
          label="检测时间"
          prop="detectionTime"
          min-width="170"
          show-overflow-tooltip
        /> -->
        <el-table-column fixed="right" label="操作" width="80">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              :disabled="!scope.row.detectionEquipCode"
              link
              @click="openDialogdetail(scope.row)"
              ><i-ep-search />
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <qdasDetectionData-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import { filterOrder } from "@/utils/commonHooks";
import dayjs from "dayjs";
defineOptions({
  name: "CDBQDASDETECTIONDATA",
  inheritAttrs: false,
});

const props = defineProps({
  isComponet: {
    type: Boolean,
    default: false,
  },
});

const { isComponet } = toRefs(props);
// 请求参数
const requestApi = "/pqd-etl/qDasDataQuery/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = reactive({
  sort: {
    column: "",
    orderBy: "",
  },
});

// 初始化搜索参数数据
const searchParamInit = {
  result: "",
  detectionEquipCode: "",
  processEquipCode: "",
  partQrCode: "",
  detectionTimeSearch: [
    dayjs().subtract(24, "hour").format("YYYY-MM-DD HH:mm:ss"),
    dayjs().endOf("day").format("YYYY-MM-DD HH:mm:ss"),
  ],
  detectionTimeStart: dayjs()
    .subtract(24, "hour")
    .format("YYYY-MM-DD HH:mm:ss"),
  detectionTimeEnd: dayjs().endOf("day").format("YYYY-MM-DD HH:mm:ss"),
};

// 数据请求错误后处理
function requestError() {}

// const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

function dataCallBack(res: any) {
  // const mockObj = {
  //   id: "671f2b00aa6500312aa32cda",
  //   paramIndex: 1,
  //   result: "0",
  //   paramValueStatus: null,
  //   paramValue: "6.0278752",
  //   detectionTime: "2023-05-11 10:04:34",
  //   detectionEvent: null,
  //   programId: "1850782132104892418",
  //   detectionEquipCode: "M1000795",
  //   processEquipCode: "AL01",
  //   paramCode: "1",
  //   paramName: "λ???",
  //   partQrCode: null,
  //   partCode: null,
  //   createTime: "2024-10-28 14:10:20",
  //   dfxDataLineIndex: 3,
  // };
  // res.push(mockObj);
  return res;
}

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack,
  requestError
);

onMounted(() => {
  getTableList();
  // getEquipTypeList();
  getEquipProduceList();
  // 在组件挂载后检查屏幕大小
  // 添加事件监听，以便在屏幕大小变化时更新条件
  window.addEventListener("resize", checkScreenSize);
});
// 排序
// 监听表格排序方法
function onTableSortChanged(column: any) {
  const { prop, order } = column;
  console.log(prop, order);

  initParam.sort = {
    column: prop,
    orderBy: filterOrder(order),
  };
}
// 监听页面 initParam 改化，重新获取表格数据
watch(() => initParam, getTableList, { deep: true });
const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(item: any) {
  request({
    url: `/pqd-etl/qDasDataQuery/get/${item.id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开设备故障信息表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "质量数据详情";
  getInfo(roleObj);
  addDialog.readvisible = true;
}

/** 不能打开设备故障信息表单弹窗 详情 */
function canNotOpenDialog(roleObj?: any) {
  ElMessage.info("检具编号为空，无法查看详情");
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

const cardSpan = ref(changeSpan(window.innerWidth));

onUnmounted(() => {
  // 清理事件监听器
  window.removeEventListener("resize", checkScreenSize);
});

const checkScreenSize = () => {
  cardSpan.value = changeSpan(window.innerWidth);
};

// 共60份  60/2
function changeSpan(innerWidth: number) {
  if (innerWidth < 768) {
    return 12;
  } else if (innerWidth >= 768 && innerWidth < 992) {
    return 12;
  } else if (innerWidth >= 992 && innerWidth < 1200) {
    return 8;
  } else if (innerWidth >= 1200 && innerWidth < 1500) {
    return 8;
  } else if (innerWidth >= 1500 && innerWidth < 1920) {
    return 6;
  } else if (innerWidth >= 1920) {
    return 5;
  }
}

function getcreateTime(data: any) {
  if (data) {
    searchParam.value.detectionTimeStart = data[0];
    searchParam.value.detectionTimeEnd = data[1];
  } else {
    searchParam.value.detectionTimeStart = "";
    searchParam.value.detectionTimeEnd = "";
  }
}

// 获取设备类型下拉框
const equipProduceList: any = ref([]);
const getEquipProduceList = async () => {
  const res: any = await request({
    url: "/mdm/mdmprocessequip/getList",
    method: "post",
    data: {},
  });
  if (res.code === 200) {
    equipProduceList.value = res.data;
  }
};
</script>
<style lang="scss" scoped>
@import url("@/styles/cardlist.scss");
</style>
